package com.jztd.servone.invoice.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.xbatis.core.mybatis.mapper.context.Pager;
import com.jztd.platfrom.base.annotation.UnifiedResponseBody;
import com.jztd.platfrom.base.exception.BusinessException;
import com.jztd.servone.emun.InvoiceStatusEnum;
import com.jztd.servone.invoice.dto.InvoiceRecordDTO;
import com.jztd.servone.invoice.param.ApplyInvoiceDetailsParam;
import com.jztd.servone.invoice.param.BasePageParam;
import com.jztd.servone.invoice.param.CancelInvoiceParam;
import com.jztd.servone.invoice.po.InvoiceRecord;
import com.jztd.servone.invoice.service.InvoiceRecordService;
import com.jztd.servone.invoice.service.InvoiceServiceFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 开票管理
 */
@UnifiedResponseBody
@RestController
@RequestMapping("/servone/invoice")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InvoiceController {
    private final InvoiceServiceFactory invoiceServiceFactory;
    private final InvoiceRecordService invoiceRecordService;

    /**
     * 申请开票
     **/
    @PostMapping("/applyInvoice")
    public Boolean applyInvoice(@RequestBody ApplyInvoiceDetailsParam param) {
        param.checkData();
        if(ObjectUtil.isNotEmpty(param.getMerge()) && param.getMerge()){
            // 先检查可以合并开票的数据
//            return invoiceServiceFactory.getService("").applyInvoice(param);
        }
        InvoiceRecord invoiceRecord = invoiceServiceFactory.getService(param.getClientCode()).applyInvoice(param);
        invoiceRecord.setTenant(param.getClientCode());
        invoiceRecordService.addInvoiceRecord(invoiceRecord);
        if(InvoiceStatusEnum.FAIL.getCode().equals(invoiceRecord.getInvoiceStatus())){
            throw new BusinessException("开票失败："+invoiceRecord.getInvoiceFailureReason());
        }
        return Boolean.TRUE;
    }

    /**
     * 作废发票
     **/
    @PostMapping("/cancelInvoice")
    public Boolean cancelInvoice(@RequestBody List<CancelInvoiceParam> param) {
        param.stream().forEach(p -> invoiceServiceFactory.getService(p.getClientCode()).cancelInvoice(p));
        return true;
    }

    /**
     * 开票记录
     */
    @GetMapping("/getInvoiceRecord")
    public Pager<InvoiceRecordDTO> getInvoiceRecordList(BasePageParam pageParam) {
        return invoiceRecordService.getInvoiceRecordList(pageParam);
    }

}
